package com.itheima.tlias84.controller;

import com.itheima.tlias84.annotation.Log;
import com.itheima.tlias84.dto.SelectEmpDetailDTO;
import com.itheima.tlias84.entity.Emp;
import com.itheima.tlias84.po.InsertEmpParam;
import com.itheima.tlias84.po.SelectEmpPageParam;
import com.itheima.tlias84.po.UpdateEmpParam;
import com.itheima.tlias84.service.EmpService;
import com.itheima.tlias84.utils.ResultUtil;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/emps")
public class EmpController {

    @Resource
    EmpService empService;

    @GetMapping
    public ResultUtil selectEmpByPage(SelectEmpPageParam param) {
        //参数校验：在controller层中实现-->page、pageSize不能为空,且至少>0
        if (Objects.isNull(param.getPage()) || Objects.isNull(param.getPageSize())) {
            return ResultUtil.fail("分页参数不存在");
        }
        return empService.selectEmpByPage(param);
//        List<SelectEmpDTO> list = empService.selectEmpByPage(param);
//        HashMap<String, Object> map = new HashMap<>();
//        map.put("total",list.size());
//        map.put("rows",list);
//        return ResultUtil.success(map);
    }

    //                           @RequestParam 必传参数，不为null
    @Log
    @DeleteMapping
    public ResultUtil batchDelete(@RequestParam("ids") List<Integer> ids) {
        //controller层：参数校验
        if (ids.isEmpty()) {
            return ResultUtil.fail("请选择需要删除的id");
        }
        int flag = empService.batchDelete(ids);
        return ResultUtil.success(flag);
    }

    //                             @Validated启动注解校验
    @Log
    @PostMapping
    public ResultUtil insertEmp(@Validated @RequestBody InsertEmpParam param) {
        int i = empService.insertEmp(param);
        return i == 0 ? ResultUtil.fail("失败") : ResultUtil.success("成功");
    }

    @GetMapping("/{id}")
    public ResultUtil selectEmpById(@PathVariable("id") Integer id) {
//                                @PathVariable 路径传参
        SelectEmpDetailDTO dto = empService.selectEmpById(id);
        return ResultUtil.success(dto);
    }

    @Log
    @PutMapping
    public ResultUtil updateEmp(@RequestBody UpdateEmpParam param) {
        int updated = empService.updateEmp(param);
        //需要通过id查询员工信息的sql中，回显id，否则修改失败-->前端没搞好
        return updated == 0 ? ResultUtil.fail("更新失败") : ResultUtil.success("更新成功");
    }

    @GetMapping("/list")
    public ResultUtil selectAllEmp() {
        List<Emp> list = empService.selectEmpAll();
        return ResultUtil.success(list);
    }
}
